<template>
  <div class="basicInfo flowCloumn">
    <div class="constentTop flowWrap" v-if="showBtn">
      <span class="topBtn">
        <el-popover
          placement="bottom"
          width="60"
          trigger="click"
          class="popoverBtn"
          v-if="showAddBtn"
        >
          <div class="addBtn" @click="toAdd('root')">在根节点新建</div>
          <div class="addBtn" @click="toAdd('current')">在当前节点新建</div>
          <el-button
            slot="reference"
            icon="el-icon-plus"
            class="el-button--primary"
            size="mini"
            ref="addBtn"
          >新建</el-button>
        </el-popover>
        <el-button
          class="el-button--primary"
          size="mini"
          icon="el-icon-check"
          @click="submit"
          v-if="showSaveBtn"
        >保存</el-button>
        <el-button
          class="el-button--primary"
          size="mini"
          icon="el-icon-delete"
          @click="deleteRow"
          v-if="showDeleteBtn"
        >删除</el-button>
        <el-button
          class="el-button--primary"
          size="mini"
          icon="el-icon-share"
          @click="moveMethods"
          v-if="showDeleteBtn"
        >移动节点</el-button>
        <el-button
          class="el-button--primary"
          size="mini"
          icon="el-icon-check"
          @click="cancel"
          v-if="showCanceln"
        >取消</el-button>
      </span>
    </div>
    <div class="constentBttom flowWrap">
      <div class="constentmain w100" v-if="showMain">
        <dividerTitle :title="'基本信息'"></dividerTitle>
        <div class="w100">
          <!-- <div class="imgBlock">
            <img src="@/assets/img/equipment.jpg" width="100%" />
          </div>-->
          <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData"></editForm>
        </div>
        <div v-if="showEntity">
          <dividerTitle :title="'设备参数'"></dividerTitle>
          <editForm :formConfig="entityConfig" ref="entityForm" :formData="entityData"></editForm>
        </div>
      </div>
    </div>
    <moveTree
      v-if="showSelete"
      :currentNode="currentNode"
      @changeSelete="submitNode"
      :showSelete.sync="showSelete"
    ></moveTree>
  </div>
</template>
<script>
import {
  getConfigApi,
  getEquipment,
  updateApi, //修改
  insertApi, //新增
  deleteApi, //删除
  moveNode,
  getFloorApi //获取层级数据
} from "@/api/equipmentLedger/equipmentManage";
import moveTree from "./moveTree";
export default {
  props: {
    //当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      }
    },
    menuType: {
      type: String,
      default: "details"
    }
  },
  components: { moveTree },
  data() {
    return {
      queryName: "",
      addType: "",
      pageType: "edit",
      hideBtn: true,
      showSelete: false,
      treeNode: {},
      formData: {},
      entityData: {},
      showMain: false,
      basicConfig: {
        itemArr: []
      },
      entityConfig: {
        itemArr: []
      },
      paramsList: [],
      beforeNode: {},
      afterNode: {},
      deptOption: [],
      deptOption1: []
    };
  },
  watch: {
    currentNode: {
      handler(val) {
        this.treeNode = Object.assign({}, val);
        this.pageType = this.menuType;
        this.changeItem();
        this.getDetails();
      },
      deep: true
    }
  },
  computed: {
    isVirtual() {
      return this.treeNode.isVirtual == 1;
    },
    showEntity() {
      return this.treeNode.isVirtual == 0 && this.entityConfig.itemArr.length;
    },
    showAddBtn() {
      return this.pageType != "add";
    },
    showCanceln() {
      return this.pageType == "add";
    },
    showSaveBtn() {
      return this.pageType == "add" || this.treeNode.id;
    },
    showDeleteBtn() {
      //新增的时候
      return this.treeNode.id && this.pageType != "add";
    },
    showBtn() {
      return this.pageType != "details";
    }
  },
  created() {
    // this.getFloor();
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.pageType = this.menuType;
    },
    getFloor() {
      let { id, parentId } = this.treeNode;
      let from = {
        id
      };
      if (parentId != 0) {
        from.parentId = parentId;
      }
      //新建设备时
      if (this.addType == "root") {
        //根节点新建
        from.id = "";
        from.parentId = "";
      } else if (this.addType == "current") {
        //在当前节点新建
        from.id = "";
        from.parentId = this.treeNode.id;
      }
      getFloorApi(from).then(res => {
        this.setConfig(res.data);
      });
    },
    setConfig(data) {
      let itemArr = [
        {
          label: "设备名称",
          prop: "name",
          type: "text",
          required: true,
          span: 8
        },
        {
          label: "节点类型",
          prop: "isVirtual",
          trigger: "change",
          type: "radio",
          radioOption: this.$store.getters["dirtData"]("equipment_node_type"),
          methods: obj => {
            this.treeNode.isVirtual = obj.value;
            this.changeItem();
          },
          span: 8,
          required: true
        },

        {
          label: "多选组织",
          prop: "deptName", //多选时，字段要为数组类型
          propArr: "deptNameArr",
          idsStr: "deptId",
          multiple: true, //是否多选
          isOutOrg: false,//是否事外单位
          option: this.deptOption, //this.deptOption
          type: "dept-select", //类型
          trigger: "change",
          methods: obj => {},
          span: 8
        },
        {
          label: "组织",
          prop: "deptName1", //多选时，字段要为数组类型
          propArr: "deptNameArr1",
          idsStr: "deptId1",
          multiple: false, //是否多选
          isOutOrg: false, //是否时外单位
          option: this.deptOption1, //this.deptOption1
          type: "dept-select", //类型
          trigger: "change",
          methods: obj => {},
          span: 8
        },
        {
          label: "多选申请人",
          prop: "userName", //多选时，字段要为数组类型
          propArr: "userArr",
          idsStr: "userId",
          multiple: true, //是否多选
          isOutOrg: false, //是否时外单位
          option: this.userOption, //this.deptOption1
          type: "user-select", //类型
          trigger: "change",
          methods: obj => {},
          span: 8
        },
        {
          label: "申请人",
          prop: "userName1", //多选时，字段要为数组类型
          propArr: "userArr1",
          idsStr: "userId1",
          multiple: false, //是否多选
          isOutOrg: false, //是否时外单位
          allowCreate: true, //是否允许创建条目
          option: this.userOption1, //this.deptOption1
          type: "user-select", //类型
          trigger: "change",
          methods: obj => {},
          span: 8
        },
        // {
        //     label: "申请人",
        //     prop: "updateByName",
        //     idsStr: "updateBy",
        //     type: "user",
        //     trigger: "change",
        //     methods: obj => {},
        //     required: true,
        //     span: 8
        //   },
        // {
        //   label: "关联组织",
        //   prop: "deptName",
        //   idsStr: "deptId",
        //   type: "dept",
        //   trigger: "change",
        //   methods: obj => {},
        //   required: true,
        //   span: 8
        // },
        {
          type: "select",
          label: "所属层级",
          prop: "floor",
          trigger: "change",
          required: true,
          selectOption: data,
          formatter: val => {
            return this.$store.getters["fineDirtDataName"](
              "equipment_level",
              val
            );
          },
          disabledOp: (val, option) => {
            let obj = option.find(i => i.value == val);
            return obj.disabled;
          },
          span: 8
        },
        // {
        //   type: "deviceClassify",
        //   label: "设备分类",
        //   prop: "typeName",
        //   idsStr: "typeId",
        //   placeholder: "请选择设备分类",
        //   required: true,
        //   span: 8,
        //   methods: arr => {
        //     //获取相应分类的参数信息
        //     if (arr[0]) {
        //       this.getConfig(arr[0].id);
        //     } else {
        //       //删除设备分类时
        //       this.paramsList = [];
        //       this.entityConfig.itemArr = [];
        //     }
        //   }
        // },
        {
          type: "deviceClassify",
          label: "设备分类",
          prop: "typeName",
          idsStr: "typeId",
          placeholder: "请选择设备分类",
          required: true,
          multiple: true,
          maxSelectNum: 3,
          filterMethod: data => {
            data.map(i => {
              if (i.isVirtual == "1") {
                //逻辑分类
                i.disabled = true;
              }
            });
            return data;
          },
          span: 8,
          methods: arr => {
            //获取相应分类的参数信息
            if (arr[0]) {
              this.getConfig(arr[0].id);
            } else {
              //删除设备分类时
              this.paramsList = [];
              this.entityConfig.itemArr = [];
            }
          }
        },
        {
          type: "deviceClassify",
          label: "设备分类1",
          prop: "typeName1",
          idsStr: "typeId1",
          placeholder: "请选择设备分类",
          required: true,
          span: 8,
          methods: arr => {}
        }
      ];
      this.basicConfig.itemArr = itemArr;
      this.changeItem();
      if (this.pageType == "details") {
        this.basicConfig.itemArr.map(i => (i.disabled = true));
      }
      this.showMain = true;
    },
    //获取节点详情
    getDetails() {
      getEquipment(this.treeNode.id).then(res => {
        let data = res.data;
        /* 测试数据 */
        //组织
        data.deptNameArr = [data.deptId];
        data.deptNameArr1 = data.deptId;
        data.deptName1 = data.deptName;
        data.deptId1 = data.deptId;
        //初始化组件Option选项值
        this.deptOption = [
          {
            label: data.deptName,
            value: data.deptId
          }
        ];
        this.deptOption1 = [
          {
            label: data.deptName,
            value: data.deptId
          }
        ];
        //用户
        data.userName = "张三";
        data.userId = "123";
        data.userName1 = "李四";
        data.userId1 = "321";
        data.userArr = [data.userId];
        data.userArr1 = data.userId1;
        //初始化组件Option选项值
        this.userOption = [
          {
            label: data.userName,
            value: data.userId
          }
        ];
        this.userOption1 = [
          {
            label: data.userName1,
            value: data.userId1
          }
        ];
        // data.deptIdArr = [];

        //获取当前节点对应的所属层级可选值，并设置editForm的Config.itemArr值
        this.getFloor();
        this.formData = data;
        this.paramsList = data.paramsList;
        this.setEntityConfig(data.paramsList);
      });
    },
    //设置实体类节点参数表单
    setEntityConfig(data) {
      let entityItem = [];
      let entityFormData = {};
      data.map(i => {
        entityFormData[i.paramId] = i.paramValue;
        let item = {
          label: i.paramName,
          prop: i.paramId,
          idsStr: i.paramResult,
          type: i.dataType,
          required: i.must,
          span: 8
        };
        if (["radio", "select"].includes(i.dataType)) {
          let enterValue = i.dataText.split(",");
          let option = [];
          enterValue.map(j => {
            let optionItem = {
              value: j,
              label: j
            };
            option.push(optionItem);
          });
          let optionName = i.dataType + "Option";
          item[optionName] = option;
        }
        entityItem.push(item);
      });
      if (this.pageType == "details") {
        entityItem.map(i => (i.disabled = true));
      }
      this.entityConfig.itemArr = entityItem;
      this.entityData = entityFormData;
    },
    //获取实体节点的参数列表
    getConfig(id) {
      getConfigApi(id).then(res => {
        this.paramsList = res.data;
        this.setEntityConfig(res.data);
      });
    },
    //新建
    toAdd(type) {
      this.addType = type;
      this.$refs.addBtn.$el.click();
      this.pageType = "add";
      this.getFloor();
      this.treeNode.isVirtual = "1";
      this.formData = { isVirtual: "1" };
      this.entityConfig.itemArr = [];
    },
    //保存
    async submit() {
      let basicData = await this.$refs.basicForm.getFormData();
      if (this.isVirtual) {
        basicData.typeName = "";
        basicData.typeId = "";
      }
      if (this.pageType == "add") {
        //新增的时候
        if (this.addType == "root") {
          basicData.parentId = "";
          basicData.parentName = "";
        } else {
          let { id, name } = this.treeNode;
          basicData.parentId = id;
          basicData.parentName = name;
        }
      }
      const actionApi = queryData => {
        return queryData.id ? updateApi(queryData) : insertApi(queryData);
      };
      if (this.showEntity) {
        //有实体参数
        let entityData = await this.$refs.entityForm.getFormData();
        this.entityData = entityData;
        //把实体参数的值放进paramsList里面
        this.setEntityData(entityData);
        basicData.paramsList = this.paramsList;
      } else {
        //无实体参数
        basicData.paramsList = [];
      }
      actionApi(basicData).then(res => {
        this.$message.success("操作成功！");
        this.$emit("updateTree", "submit");
        this.addType = "";
        this.getDetails();
        this.pageType = "edit";
      });
    },
    //删除
    deleteRow() {
      let { id } = this.treeNode;
      this.$confirm(`是否确认删除`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteApi(id).then(res => {
            this.$message.success("操作成功");
            this.treeNode = {};
            this.formData = {};
            this.showMain = false;
            this.$emit("updateTree");
          });
        })
        .catch(e => {});
    },
    //移动节点
    moveMethods() {
      this.showSelete = true;
    },
    //取消新建
    cancel() {
      this.pageType = "edit";
      this.addType = "";
      this.getDetails();
    },
    //提交移动节点
    submitNode(node) {
      let form = {
        id: this.treeNode.id,
        parentId: node[0].id
      };
      moveNode(form).then(res => {
        this.$message.success("操作成功");
        this.treeNode = {};
        this.formData = {};
        this.showMain = false;
        this.$emit("updateTree");
      });
    },
    //设置实体参数的值
    setEntityData(data) {
      this.paramsList.map(i => {
        i.paramValue = data[i.paramId];
      });
    },
    //判断实体和虚节点，并控制相应项的展示与隐藏
    changeItem() {
      let arr = [].concat(this.basicConfig.itemArr);
      for (let i in arr) {
        if (["设备分类"].includes(arr[i].label)) {
          if (this.isVirtual) {
            //虚拟节点
            arr[i].isHide = true;
          } else {
            //实体节点
            arr[i].isHide = false;
          }
        }
      }
      this.basicConfig.itemArr = arr;
    }
  }
};
</script>
<style lang="less" scoped>
.basicInfo {
  .imgBlock {
    width: 300px;
    height: 150px;
  }
  .constentTop {
    justify-content: flex-end;
  }
  .queryInput {
    /deep/.el-input__inner {
      height: 30px;
      line-height: 30px;
    }
  }
  .constentmain {
    padding-top: 10px;
    margin-left: 10px;
  }
  .popoverBtn + .el-button--primary {
    margin-left: 10px;
  }
  .el-button--primary {
    background-color: #2c77f4 !important;
    border-color: #2c77f4 !important;
  }
}
.addBtn:hover {
  color: @kr-elementUI-color;
  cursor: pointer;
}
.flowCloumn {
  display: flex;
  flex-flow: column nowrap;
}
.flowWrap {
  display: flex;
  flex-flow: wrap nowrap;
}
</style>